﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Luka;

public static class CacheSetup
{
    /// <summary>
    /// 添加缓存
    /// </summary>
    /// <returns></returns>
    public static IServiceCollection AddCache(this IServiceCollection services)
    {
        var setting = InternalApp.GetSection<CacheOptions>("Cache") ?? throw new KeyNotFoundException($"{nameof(CacheSetup)}:缓存未配置");
        //是否启用
        if (setting.IsEnable)
        {
            //将Redis分布式缓存服务添加到服务中
            services.AddStackExchangeRedisCache(options =>
            {
                //用于连接Redis的配置
                options.Configuration = $"{setting.Connection},password={setting.Password}";
                //Redis实例名
                options.InstanceName = setting.InstanceName ?? "CacheInstance";
            });
            //添加自定义方法
            services.TryAddTransient<ICacheHandler, CacheHandler>();
        }
        return services;
    }
}